package com.licw.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.licw.constant.MessageConstant;
import com.licw.constant.StatusConstant;
import com.licw.dto.DishDTO;
import com.licw.dto.DishPageQueryDTO;
import com.licw.entity.Dish;
import com.licw.entity.DishFlavor;
import com.licw.entity.Setmeal;
import com.licw.exception.DeletionNotAllowedException;
import com.licw.mapper.DishFlavorMapper;
import com.licw.mapper.DishMapper;
import com.licw.mapper.SetmealDishMapper;
import com.licw.mapper.SetmealMapper;
import com.licw.result.PageResult;
import com.licw.service.DishService;
import com.licw.vo.DishVO;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

@Service
@Slf4j
public class DishServiceImpl implements DishService {

    @Resource
    private DishMapper dishMapper;
    @Resource
    private DishFlavorMapper dishFlavorMapper;

    @Resource
    private SetmealDishMapper setmealDishMapper;

    @Resource
    private SetmealMapper setmealMapper;


    @Resource
    private RedisTemplate<String, Object> redisTemplate;

    @Override
    @Transactional
    public void saveWithFlavor(DishDTO dishDTO) {
        Dish dish = new Dish();
        BeanUtils.copyProperties(dishDTO, dish);
        if (dish.getStatus() == null) {
            dish.setStatus(StatusConstant.DISABLE);
        }
        // 保存菜品
        dishMapper.insert(dish);

        List<DishFlavor> flavors = dishDTO.getFlavors();
        if (flavors == null || flavors.size() == 0) return;
        flavors.forEach((flavor) -> flavor.setDishId(dish.getId()));
        // 保存口味
        dishFlavorMapper.insertByBatch(flavors);

        //清理缓存数据
        String key = "dish_" + dishDTO.getCategoryId();
        cleanCache(key);

    }

    @Override
    public PageResult<DishVO> pageQuery(DishPageQueryDTO dishPageQueryDTO) {
        PageHelper.startPage(dishPageQueryDTO.getPage(), dishPageQueryDTO.getPageSize());
        Page<DishVO> dishVOPage = dishMapper.pageQuery(dishPageQueryDTO);
        long total = dishVOPage.getTotal();
        List<DishVO> dishVOList = dishVOPage.getResult();
        return new PageResult<>(total, dishVOList);
    }

    @Override
    public void deleteByIds(List<Long> ids) {
        if (ids == null || ids.size() == 0) return;
        //- 起售中的菜品不能删除
        List<Dish> dishList = dishMapper.selectByIds(ids);
        if (dishList.size() == 0) return;
        for (Dish dish : dishList) {
            if (StatusConstant.ENABLE.equals(dish.getStatus())) {
                throw new DeletionNotAllowedException(MessageConstant.DISH_ON_SALE);
            }
        }
        //- 被套餐关联的菜品不能删除
        List<Long> setmealList = setmealDishMapper.selectSetmealIdsByDishIds(ids);
        if (setmealList != null && setmealList.size() > 0) {
            throw new DeletionNotAllowedException(MessageConstant.DISH_BE_RELATED_BY_SETMEAL);
        }

        //- 删除菜品后，关联的口味数据也需要删除掉
        // 删除菜品关联的口味
        dishFlavorMapper.deleteByDishIds(ids);
        // 删除菜品
        dishMapper.deleteByIds(ids);

        // 删除对应缓存
        List<Long> categoryIds = dishList.stream()
                .map((Dish::getCategoryId))
                .distinct()
                .collect(Collectors.toList());
        for(Long categoryId : categoryIds){
            cleanCache("dish_" + categoryId);
        }
    }

    @Override
    @Transactional
    public void setStatus(Integer status, Long id) {
        Dish dish = Dish.builder().id(id).status(status).build();
        dishMapper.update(dish);
        // 删除菜品缓存
        Dish newDish = dishMapper.getById(id);
        cleanCache("dish_" + newDish.getCategoryId());

        // 如果当前菜品停售，包含当前菜品的套餐也停售
        if (StatusConstant.DISABLE.equals(status)) {
            List<Long> setmealIds = setmealDishMapper.selectSetmealIdsByDishIds(Collections.singletonList(id));
            if (setmealIds == null || setmealIds.size() == 0) return;
            for (Long setmealId : setmealIds) {
                Setmeal setmeal = Setmeal.builder().id(setmealId).status(StatusConstant.DISABLE).build();
                setmealMapper.update(setmeal);
            }
        }
    }


    @Override
    public DishVO getVOById(Long id) {
        // 获取菜品信息
        DishVO dishVO = dishMapper.selectWithFlaversById(id);
        // 获取口味信息
        List<DishFlavor> flavors = dishFlavorMapper.selectByDishId(id);
        dishVO.setFlavors(flavors);
        return dishVO;
    }

    @Override
    public void update(DishDTO dishDTO) {
        Dish dish = new Dish();
        BeanUtils.copyProperties(dishDTO, dish);
        // 修改菜品基本信息
        dishMapper.update(dish);

        // 删除原有的口味
        Long dishId = dish.getId();
        dishFlavorMapper.deleteByDishId(dishId);

        // 插入现有的口味
        List<DishFlavor> flavors = dishDTO.getFlavors()
                .stream()
                .filter(dishFlavor -> StringUtils.isNotBlank(dishFlavor.getName()))
                .peek((dishFlavor -> dishFlavor.setDishId(dishId)))
                .collect(Collectors.toList());
        if (flavors.size() == 0) return;
        dishFlavorMapper.insertByBatch(flavors);

        // 删除菜品缓存
        Dish newDish = dishMapper.getById(dishDTO.getId());
        cleanCache("dish_" + newDish.getCategoryId());
    }

    @Override
    public List<Dish> list(Long categoryId) {
        Dish dish = Dish.builder()
                .categoryId(categoryId)
                .status(StatusConstant.ENABLE)
                .build();
        return dishMapper.list(dish);
    }

    @Override
    public List<DishVO> listWithFlavor(Dish dish) {
        //构造redis中的key，规则：dish_分类id
        String key = "dish_" + dish.getCategoryId();

        // 从redis中查询缓存数据
        List<DishVO> dishVOList = (List<DishVO>) redisTemplate.opsForValue().get(key);
        if(CollectionUtils.isNotEmpty(dishVOList)){
            log.info("从redis中获取数据");
            return dishVOList;
        }

        // redis中没有缓存，从数据库中查询
        List<Dish> dishList = dishMapper.list(dish);
        dishVOList = new ArrayList<>();

        for (Dish d : dishList) {
            DishVO dishVO = new DishVO();
            BeanUtils.copyProperties(d, dishVO);

            //根据菜品id查询对应的口味
            List<DishFlavor> flavors = dishFlavorMapper.listByDishId(d.getId());

            dishVO.setFlavors(flavors);
            dishVOList.add(dishVO);
        }

        // 将查询到的数据缓存到数据库中
        redisTemplate.opsForValue().set(key, dishVOList);
        return dishVOList;
    }

    /**
     * 清理redis缓存数据
     */
    private void cleanCache(String pattern){
        Set<String> keys = redisTemplate.keys(pattern);
        if(CollectionUtils.isEmpty(keys)) return;
        redisTemplate.delete(keys);
    }
}
